﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using DLLsxs;

namespace Help
{
    public static class ALL_DataV
    {

        public static string YZM { get; set; }
        public static string Constring { get; set; }
        public static string PhotoPath { get; set; }
        public static string PushPath { get; set; }
        public static string FlowTime { get; set; }
        static void JiaoNian()
        {
            IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");
            while (true)
            {
                //Class1 yanzheng = new Class1();
                //yanzheng.Selectdog();
                //YZM = yanzheng.ReadDogZD(1800);
                //if (YZM == "-99")
                //{
                //    WriteLog.WriteW("获取加密狗客户验证码失败,系统返回终止");
                //    Began = 0;
                //    return false;
                //}
                //SchoolName = yanzheng.ReadDogZD(1850); 
                //List<Model.Sys_Component_T> ls = bl.ISys_Component_TBLL.GetListBy(u => u.ID > 0);
                //for (int i = 0; i < ls.Count; i++)
                //{


                //}
                System.Threading.Thread.Sleep(10000);
            }
            #region 加密狗操作

            #endregion

        }

        #region 返回数据库连接串
        /// <summary>
        /// 返回config配置文件数据库连接串
        /// </summary>
        /// <returns></returns>
        public static void ReturnConstring()
        {
            try
            {
                Constring = System.Configuration.ConfigurationSettings.AppSettings["con"].ToString();
                PhotoPath = System.Configuration.ConfigurationSettings.AppSettings["PhotoPath"].ToString();
                PushPath = System.Configuration.ConfigurationSettings.AppSettings["PushPath"].ToString();
                FlowTime = System.Configuration.ConfigurationSettings.AppSettings["FlowTime"].ToString();

            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取数据库连接错误：" + ex.Message);
                throw;
            }
        }
        #endregion

        #region 读取配置文件指定的值
        /// <summary>
        /// 读取配置文件指定的值
        /// </summary>
        public static string getXmlData(string type)
        {
            string strxml = "";
            XmlDocument xml = new XmlDocument();
            xml.Load(Application.StartupPath + "\\WSBX.config");
            XmlNodeList xmldebug = xml.GetElementsByTagName(type);
            if (xmldebug.Count > 1)
            {
                for (int i = 0; i < xmldebug.Count; i++)
                {
                    strxml += xmldebug[i].InnerText.Trim() + ";";
                }
            }
            else
            {
                strxml = xmldebug[0].InnerText.Trim();
            }
            return strxml;
        }
        #endregion

        #region 服务初始化方法体(数据库，配置文件信息)
        public static Queue<Model.Order_Form_T> PushQueue = new Queue<Model.Order_Form_T>();
        public static bool BeganGO()
        {
            try
            {
                #region 加密狗操作

                WriteLog.WriteW("开始验证加密狗,请等待.......");
                //Class1 yanzheng = new Class1();
                //yanzheng.Selectdog();
                //string jiami = yanzheng.ReadDogZD(50);
                //if (jiami != "SZHQWSDC#@981#X")
                //{
                //    WriteLog.WriteW("获取加密狗验证码失败,系统返回终止 加密狗返回值： " + jiami);
                //    return false;
                //}

                //WriteLog.WriteW("获取加密狗客户证成功！     加密狗返回值： "+jiami);
                YZM = "";

                #endregion

                ReturnConstring();
                WriteLog.WriteW("BeganGO()                            ReturnConstring");
                if (!Directory.Exists(Application.StartupPath + "\\Photo\\DishPhoto\\"))//判断目录是否存在
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\Photo\\DishPhoto\\");
                }
                if (!Directory.Exists(Application.StartupPath + "\\Photo\\MerPhoto\\"))//判断目录是否存在
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\Photo\\MerPhoto\\");
                }
                IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");
                WriteLog.WriteW("BeganGO()     1");

                #region 推送
                ThreadPool.QueueUserWorkItem((a) =>
                   {
                       while (true)
                       {
                           try
                           {
                               ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();
                               if (PushQueue.Count > 0)
                               {
                                   Model.Order_Form_T info = PushQueue.Dequeue();
                                   try
                                   {
                                       //if (info.Type != "200003")
                                       //{
                                       //    int opid = bl.IOrder_Oper_TBLL.GetListBy(u => u.MerID.Contains(info.FormMerID)).First().OperID;
                                       //}
                                       string MerName = bl.IOrder_Mer_TBLL.GetListBy(u => u.MerID == info.FormMerID).First().MerName;
                                       WriteLog.WriteW("推送  1");
                                       // StringBuilder Ps = new StringBuilder();
                                       string str_订单类型, str_名字;
                                       switch (info.Type)
                                       {
                                           case "200001":
                                               str_订单类型 = "普通用户订单";
                                               // str_名字 = bl.IView_UserBLL.GetListBy(u => u.AccID == info.AccID).First().AccName;
                                               str_名字 = info.AccName;
                                               break;
                                           case "200002":
                                               str_订单类型 = "企业订单";
                                               str_名字 = bl.IOrder_Organization_TBLL.GetListBy(u => u.OrgID == info.AccID).First().OrgName;
                                               break;
                                           case "200003":
                                               str_订单类型 = "派送任务：取餐地点（" + info.FormMerID + "）";
                                               WriteLog.WriteW("推送  2");
                                               //str_名字 = bl.IOrder_Organization_TBLL.GetListBy(u => u.OrgID == info.AccID).First().OrgName;
                                               str_名字 = info.AccName;
                                               WriteLog.WriteW("推送  3");
                                               break;
                                           case "200004": //通知调度员
                                               str_订单类型 = "指派任务：商户(" + info.FormMerID + ")";
                                               str_名字 = info.AccName;
                                               Help.Log.Debug("推送      ", "       1");
                                               break;
                                           default:
                                               WriteLog.WriteW("推送  4");
                                               str_订单类型 = "未知通知";
                                               str_名字 = "未知项目";
                                               break;
                                       }
                                       WriteLog.WriteW("推送  5");
                                       List<string> sl = new List<string>();

                                       if (info.Type == "200003")//(info.Type == "200003")
                                       {//用IsEva保存送餐员ID(takerID)
                                           sl = (from m in bl.IOrder_Taker_TBLL.GetListBy(u => u.TakerID == info.IsEva && u.TakerState == 1) select m.TakerOpenID).ToList();
                                       }
                                       else if (info.Type == "200004")
                                       {

                                           //用FormDishesID保存OperID
                                           // sl = (from m in bl.IOrder_Taker_TBLL.GetListBy(u => u.TakerState == 1 && u.OperID==info.IsEva && u.TakerRole == 1) select m.TakerOpenID).ToList();
                                           WriteLog.WriteW("推送  select * from Order_Taker_T where TakerRole=1 and TakerState=1 and OperID in (" + info.FormDishesID + ")");
                                           sl = (from m in bl.IOrder_Taker_TBLL.GetListBy("select * from Order_Taker_T where TakerRole=1 and TakerState=1 and OperID in (" + info.FormDishesID + ")") select m.TakerOpenID).ToList();
                                       }
                                       else
                                       {
                                           sl = (from m in bl.IOrder_MerSetWxMess_TBLL.GetListBy(u => u.MerID == info.FormMerID & u.Stat == 1) select m.OpenID).ToList();
                                       }
                                       WriteLog.WriteW("推送  6");
                                       if (sl.Count > 0)
                                       {
                                           WriteLog.WriteW("推送  7");
                                           string str = string.Join(",", sl.Where(u => true));
                                           WriteLog.WriteW("推送WX：" + str);
                                           string[] name = info.FormDisheName.Split(',');
                                           string[] nub = info.FormDishesNun.Split(',');
                                           string user = "";
                                           for (int i = 0; i < name.Length; i++)
                                           {
                                               if (i < nub.Length)
                                               {
                                                   if (i == nub.Length - 1)
                                                   {
                                                       user += name[i] + ":" + nub[i] + "份";
                                                   }
                                                   else
                                                   {
                                                       user += name[i] + ":" + nub[i] + "份" + "、";
                                                   }
                                               }
                                           }
                                           string sentime = info.SenTime.Substring(0, 4) + "-" + info.SenTime.Substring(4, 2) + "-" + info.SenTime.Substring(6, 2) + " " + info.SenTime.Substring(8, 2) + ":" + info.SenTime.Substring(10, 2);
                                           if (info.Type == "200003")
                                           {
                                               WriteLog.WriteW("SenMesToUser(" + str + "," + str_订单类型 + "," + Convert.ToDouble(info.FormPayMon) / 100.0 + "元" + "," + user + "," + str_名字 + "(手机：" + info.AccCall + ")，" + info.FormAddress + "， sentime，“”");

                                           }
                                           string jg = sc.SenMesToUser(str, str_订单类型, Convert.ToDouble(info.FormPayMon) / 100.0 + "元", "餐厅:" + MerName + " " + user, str_名字 + " (手机：" + info.AccCall + ")", info.FormAddress, sentime, "");

                                           WriteLog.WriteW("SenMesToUser  返回值：" + jg);
                                           //string jg = sc.SenMesToUser(str, str_订单类型, info.FormPayMon / 100 + "元" + "(" + info.IsPay + ")", user, str_名字 + "(手机：" + info.AccCall + ")", info.FormAddress, info.SenTime.Substring(0, 4) + "-" + info.SenTime.Substring(4, 6) + "-" + info.SenTime.Substring(6, 8) + " " + info.SenTime.Substring(8, 10) + ":" + info.SenTime.Substring(10, 12), "");
                                       }
                                       //string add = Help.ALL_DataV.PushPath + PushText;
                                       // WriteLog.WriteW("推送：" + add);
                                       //HttpWebRequest request = HttpWebRequest.Create(Help.ALL_DataV.PushPath + opid + "|您有新的订单") as HttpWebRequest;
                                       //HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                                   }
                                   catch (Exception ex)
                                   {
                                       WriteLog.WriteW("推送异常：" + ex.ToString());
                                   }
                               }
                               else
                               {
                                   Thread.Sleep(3000);
                               }
                           }
                           catch (Exception ex)
                           {
                               WriteLog.WriteW("推送线程异常:" + ex.Message);
                           }

                       }


                   });
                #endregion

                WriteLog.WriteW("BeganGO()     2");

                #region 结帐
                ThreadPool.QueueUserWorkItem((a) =>
                {
                    while (true)
                    {
                        try
                        {
                            if (DateTime.Now.ToString("HHmm") == FlowTime)
                            {
                                bl.IOrder_MerAccount_TBLL.CloseAccout();
                                Thread.Sleep(500000);
                            }
                            else
                            {
                                Thread.Sleep(50000);
                            }
                        }
                        catch (Exception ex)
                        {

                            WriteLog.WriteW("结帐线程异常:" + ex.Message);
                        }
                    }


                });
                #endregion

                #region 报表
                ThreadPool.QueueUserWorkItem((a) =>
                {
                    while (true)
                    {
                        try
                        {
                            if (DateTime.Now.ToString("HHmm") == "2358")
                            {
                                bl.IOrder_DayReport_Mer_TBLL.DayReport_Mer_T();
                                bl.IOrder_DayReport_Mer_TBLL.DayReport_DishesType_T();
                                bl.IOrder_DayReport_Mer_TBLL.DayReport_Dishes_T();
                                break;
                            }
                            else
                            {
                                Thread.Sleep(50000);
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLog.WriteW("报表线程异常:" + ex.Message);
                        }


                    }


                });
                #endregion

                #region 定时清理未支付订单
                //ThreadPool.QueueUserWorkItem((a) =>
                //{
                //    WriteLog.WriteW("进入查找未支付的订单线程");
                //    while (true)
                //    {
                //        try
                //        {
                //            bl.IOrder_Form_TBLL.ClearForm();
                //            Thread.Sleep(30000);
                //        }
                //        catch (Exception ex)
                //        {
                //            WriteLog.WriteW("定时清理未支付订单线程异常:" + ex.Message);
                //            Thread.Sleep(30000);
                //        }
                //    }
                //});
                #endregion

                WriteLog.WriteW("服务启动成功");

                return true;
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("服务启动时初始化失败，错误信息：" + ex.Message);
                return false;
            }
        }
        #endregion
    }
}
